#coding=utf-8
from django.db import models
import stscraper
from share import Share

class Exday(models.Model):
    
    date = models.DateField()
    share = models.ForeignKey(Share)
    pre = models.ForeignKey('self', unique=True, null=True, blank=True)
    
    def get_nextday(self):
        a = self.exday_set.all()
        if a:
            return a[0]
        return None
    
    def get_price(self):
        a = self.price_set.all()
        if a:
            return a[0]
        return None
    
    def get_ts(self):
        s = self.share
        for t in s.tradableshare_set.all().order_by('-date'):
            if self.date >= t.date:
                return t.quantity
    
    def get_avgprice(self):
        a = self.averageprice_set.all()
        if a:
            return a[0]
        return None
    
    def get_avgvolume(self):
        a = self.averagevolume_set.all()
        if a:
            return a[0]
        return None
      
    def prenday(self, n):
        cur = self
        for i in range(n):
            pre = cur.pre
            if not pre: return None
            cur = pre
        return cur 
    
    def afternday(self, n):
        cur = self
        for i in range(n):
            next = cur.next
            if not next: return None
            cur = next
        return cur
     
    def prenday_ps(self, n):
        '''不包括当天.'''
        e = self
        
        r = []
        for i in range(n):
            if not e.pre:return r
            r.append( e.pre.price )
            e = e.pre
        
        return r
    
    def highest(self, n):
        '''前n天价格最高点'''
        ps = self.prenday_ps(n)
    
        if len(ps) != n:
            return None
    
        highs = [p.high for p in ps]
        return max(highs)
    
    def lowest(self, n):
        '''前n天价格最高点'''
        ps = self.prenday_ps(n)
    
        if len(ps) != n:
            return None
    
        lows = [p.low for p in ps]
        return min(lows)
    
    def get_afternday_change(self, n=5):
        ae = self.afternday(n)
        if not ae:return None
        aeend = ae.prcie.end
        end = self.price.end
        
        change = float( (aeend-end)*100/end)
        return change
    
    next=property(fget=get_nextday)
    price=property(fget=get_price)
    ts = property(fget=get_ts)
    avgprice=property(fget=get_avgprice)
    avgvolume=property(fget=get_avgvolume)
    
    def __unicode__(self):
        jyr = unicode('交易日', 'u8')
        return "%s:%sof%s"%(self.date, jyr, self.share)
    
    class Admin:pass
    class Meta:
        app_label = 'stock'
        unique_together = ("share", "date")    